import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../../../common/utils/toast_util.dart';
import '../../../../../common/api/activity_api.dart';
import '../../../../../common/models/index.dart';
import 'dart:developer' as developer;

/// 活动管理页面
/// 提供活动的详细管理功能，包括参与者管理、活动设置等
class ActivityManagementPage extends StatefulWidget {
  /// 要管理的活动数据
  final ActivityData? activityData;
  
  const ActivityManagementPage({
    super.key,
    this.activityData,
  });

  @override
  State<ActivityManagementPage> createState() => _ActivityManagementPageState();
}

class _ActivityManagementPageState extends State<ActivityManagementPage> {
  // 真实参与者数据
  List<ActivityParticipant> participants = [];
  
  // 加载状态
  bool isLoading = false;
  String? errorMessage;
  
  @override
  void initState() {
    super.initState();
    _loadParticipants();
  }
  
  /// 加载参与者数据
  Future<void> _loadParticipants() async {
    if (widget.activityData == null) {
      if (mounted) {  // 检查widget是否还在树中
        setState(() {
          errorMessage = '未找到活动数据';
        });
      }
      return;
    }
    
    if (mounted) {  // 检查widget是否还在树中
      setState(() {
        isLoading = true;
        errorMessage = null;
      });
    }
    
    try {
      developer.log('🔄 开始加载活动参与者数据');
      
      final response = await ActivityApi.getActivityParticipants(
        activityId: widget.activityData!.activityId,
      );
      
      if (response.isSuccess && response.data != null) {
        if (mounted) {  // 检查widget是否还在树中
          setState(() {
            participants = response.data!.participants;
            isLoading = false;
          });
        }
        
        developer.log('✅ 参与者数据加载成功，共${participants.length}人');
      } else {
        if (mounted) {  // 检查widget是否还在树中
          setState(() {
            errorMessage = response.message;
            isLoading = false;
          });
        }
        
        developer.log('❌ 参与者数据加载失败: ${response.message}');
      }
    } catch (e) {
      if (mounted) {  // 检查widget是否还在树中
        setState(() {
          errorMessage = '加载参与者数据失败: $e';
          isLoading = false;
        });
      }
      
      developer.log('💥 加载参与者数据异常: $e');
    }
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFD94841),
      appBar: AppBar(
        leading: IconButton(
          onPressed: () {
            Get.back();
          },
          icon: const Icon(Icons.arrow_back_ios_new_outlined),
        ),
        backgroundColor: Colors.transparent,
        elevation: 0,
        title: Text(
          widget.activityData?.activityTitle ?? '活动管理',
          style: const TextStyle(
            color: Colors.white,
            fontSize: 18,
            fontWeight: FontWeight.w600,
          ),
        ),
        centerTitle: true,
        iconTheme: const IconThemeData(color: Colors.white),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 参与者管理
            _buildParticipantsSection(),
          ],
        ),
      ),
    );
  }


  /// 构建参与者管理区域
  Widget _buildParticipantsSection() {
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Row(
              children: [
                Icon(Icons.people, color: Colors.blue, size: 24),
                SizedBox(width: 8),
                Text(
                  '参与者管理',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),
            
            // 加载状态或参与者列表
            if (isLoading)
              Container(
                width: double.infinity,
                padding: const EdgeInsets.symmetric(vertical: 40),
                decoration: BoxDecoration(
                  color: Colors.grey.shade50,
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(color: Colors.grey.shade200),
                ),
                child: const Column(
                  children: [
                    CircularProgressIndicator(),
                    SizedBox(height: 16),
                    Text(
                      '正在加载参与者数据...',
                      style: TextStyle(
                        color: Colors.grey,
                        fontSize: 16,
                      ),
                    ),
                  ],
                ),
              )
            else if (errorMessage != null)
              Container(
                width: double.infinity,
                padding: const EdgeInsets.symmetric(vertical: 40),
                decoration: BoxDecoration(
                  color: Colors.red.shade50,
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(color: Colors.red.shade200),
                ),
                child: Column(
                  children: [
                    Icon(Icons.error_outline, color: Colors.red.shade400, size: 48),
                    const SizedBox(height: 8),
                    Text(
                      errorMessage!,
                      style: TextStyle(
                        color: Colors.red.shade600,
                        fontSize: 16,
                      ),
                      textAlign: TextAlign.center,
                    ),
                    const SizedBox(height: 16),
                    ElevatedButton(
                      onPressed: _loadParticipants,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.red,
                        foregroundColor: Colors.white,
                      ),
                      child: const Text('重试'),
                    ),
                  ],
                ),
              )
            else if (participants.isEmpty)
              Container(
                width: double.infinity,
                padding: const EdgeInsets.symmetric(vertical: 40),
                decoration: BoxDecoration(
                  color: Colors.grey.shade50,
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(color: Colors.grey.shade200),
                ),
                child: Column(
                  children: [
                    Icon(Icons.person_off, color: Colors.grey.shade400, size: 48),
                    const SizedBox(height: 8),
                    Text(
                      '暂无参与者',
                      style: TextStyle(
                        color: Colors.grey.shade600,
                        fontSize: 16,
                      ),
                    ),
                  ],
                ),
              )
            else
              _buildParticipantsList(),
          ],
        ),
      ),
    );
  }

  /// 构建参与者列表
  Widget _buildParticipantsList() {
    return Wrap(
      spacing: 16, // 水平间距
      runSpacing: 16, // 垂直间距
      children: participants.map((participant) => _buildParticipantAvatar(participant)).toList(),
    );
  }

  /// 构建参与者头像
  Widget _buildParticipantAvatar(ActivityParticipant participant) {
    return Stack(
      clipBehavior: Clip.none, // 允许子组件超出边界
      children: [
        Column(
          children: [
            ClipRRect(
              borderRadius: BorderRadius.circular(35),
              child: Image.network(
                participant.userAvatarUrl.isNotEmpty 
                    ? participant.userAvatarUrl 
                    : 'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_16.webp',
                width: 70,
                height: 70,
                fit: BoxFit.cover,
                errorBuilder: (context, error, stackTrace) {
                  return Container(
                    width: 70,
                    height: 70,
                    decoration: BoxDecoration(
                      color: Colors.grey.shade300,
                      borderRadius: BorderRadius.circular(35),
                    ),
                    child: Icon(
                      Icons.person,
                      color: Colors.grey.shade600,
                      size: 35,
                    ),
                  );
                },
              ),
            ),
            const SizedBox(height: 8),
            SizedBox(
              width: 70,
              child: Text(
                participant.username.isNotEmpty ? participant.username : '用户${participant.userId}',
                style: const TextStyle(
                  fontSize: 12,
                  fontWeight: FontWeight.w500,
                ),
                textAlign: TextAlign.center,
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ],
        ),
        // 删除按钮
        Positioned(
          top: -8,
          right: -8,
          child: GestureDetector(
            onTap: () => _removeParticipant(participant),
            child: Container(
              width: 26,
              height: 26,
              decoration: BoxDecoration(
                color: Colors.red,
                shape: BoxShape.circle,
                border: Border.all(
                  color: Colors.white,
                  width: 2,
                ),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withValues(alpha: 0.2),
                    blurRadius: 4,
                    offset: const Offset(0, 2),
                  ),
                ],
              ),
              child: const Icon(
                Icons.remove,
                color: Colors.white,
                size: 14,
              ),
            ),
          ),
        ),
      ],
    );
  }

  /// 移除参与者
  void _removeParticipant(ActivityParticipant participant) {
    Get.dialog(
      Dialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16),
        ),
        child: Container(
          padding: const EdgeInsets.all(24),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(16),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 图标
              Container(
                width: 64,
                height: 64,
                decoration: BoxDecoration(
                  color: Colors.red.withValues(alpha: 0.1),
                  shape: BoxShape.circle,
                ),
                child: const Icon(
                  Icons.person_remove,
                  color: Colors.red,
                  size: 32,
                ),
              ),
              const SizedBox(height: 16),
              
              // 标题
              const Text(
                '移除参与者',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.w600,
                  color: Colors.black87,
                ),
              ),
              const SizedBox(height: 8),
              
              // 内容
              Text(
                '确定要从活动中移除「${participant.username}」吗？',
                style: TextStyle(
                  fontSize: 14,
                  color: Colors.grey.shade600,
                ),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 24),
              
              // 按钮
              Row(
                children: [
                  Expanded(
                    child: OutlinedButton(
                      onPressed: () => Get.back(),
                      style: OutlinedButton.styleFrom(
                        side: BorderSide(color: Colors.grey.shade300),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8),
                        ),
                        padding: const EdgeInsets.symmetric(vertical: 12),
                      ),
                      child: const Text(
                        '取消',
                        style: TextStyle(
                          color: Colors.black54,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: ElevatedButton(
                      onPressed: () async {
                        Get.back(); // 先关闭对话框
                        await _deleteParticipant(participant);
                      },
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.red,
                        foregroundColor: Colors.white,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8),
                        ),
                        padding: const EdgeInsets.symmetric(vertical: 12),
                        elevation: 0,
                      ),
                      child: const Text(
                        '确定移除',
                        style: TextStyle(
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 删除参与者的具体实现
  Future<void> _deleteParticipant(ActivityParticipant participant) async {
    if (widget.activityData == null) {
      ToastUtil.error('未找到活动数据');
      return;
    }

    try {
      developer.log('🔄 开始删除参与者: ${participant.username}');
      
      // 显示加载提示
      ToastUtil.info('正在移除参与者...');
      
      final response = await ActivityApi.deleteActivityParticipant(
        activityId: widget.activityData!.activityId,
        userId: participant.userId,
      );
      
      if (response.isSuccess) {
        // 删除成功，从本地列表中移除
        if (mounted) {  // 检查widget是否还在树中
          setState(() {
            participants.removeWhere((p) => p.userId == participant.userId);
          });
        }
        
        ToastUtil.success('参与者已成功移除');
        developer.log('✅ 参与者删除成功: ${participant.username}');
      } else {
        ToastUtil.error('移除失败: ${response.message}');
        developer.log('❌ 参与者删除失败: ${response.message}');
      }
    } catch (e) {
      ToastUtil.error('移除参与者失败: $e');
      developer.log('💥 删除参与者异常: $e');
    }
  }
}